'use client'

import React, { useState, useEffect, useCallback } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { Textarea } from "@/components/ui/textarea"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Badge } from "@/components/ui/badge"
import { 
  Plus, 
  Edit, 
  Trash2, 
  Upload, 
  Eye, 
  EyeOff, 
  MoveUp, 
  MoveDown,
  Save,
  X,
  ExternalLink,
  Calendar,
  Image as ImageIcon
} from 'lucide-react'
import { toast } from 'sonner'

interface BannerItem {
  id: number
  title: string
  description?: string
  imageUrl: string
  linkUrl?: string
  linkType: 'internal' | 'external' | 'none'
  isActive: boolean
  sortOrder: number
  startTime?: Date
  endTime?: Date
  createdAt: Date
  updatedAt: Date
}

interface BannerForm {
  title: string
  description: string
  linkUrl: string
  linkType: 'internal' | 'external' | 'none'
  isActive: boolean
  sortOrder: number
  startTime: string
  endTime: string
  image?: File
}

export default function BannerManagement() {
  const [banners, setBanners] = useState<BannerItem[]>([])
  const [loading, setLoading] = useState(true)
  const [showModal, setShowModal] = useState(false)
  const [editingBanner, setEditingBanner] = useState<BannerItem | null>(null)
  const [form, setForm] = useState<BannerForm>({
    title: '',
    description: '',
    linkUrl: '',
    linkType: 'internal',
    isActive: true,
    sortOrder: 1,
    startTime: '',
    endTime: ''
  })
  const [imagePreview, setImagePreview] = useState<string>('')

  // 获取轮播图列表
  const fetchBanners = useCallback(async () => {
    try {
      setLoading(true)
      const response = await fetch('/v1/banner/admin/list', {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      const data = await response.json()
      
      if (data.success) {
        setBanners(data.data || [])
      } else {
        toast.error(data.message || '获取轮播图列表失败')
      }
    } catch (error) {
      console.error('获取轮播图列表失败:', error)
      toast.error('获取轮播图列表失败')
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    fetchBanners()
  }, [fetchBanners])

  // 重置表单
  const resetForm = () => {
    setForm({
      title: '',
      description: '',
      linkUrl: '',
      linkType: 'internal',
      isActive: true,
      sortOrder: banners.length + 1,
      startTime: '',
      endTime: ''
    })
    setImagePreview('')
    setEditingBanner(null)
  }

  // 打开新建/编辑弹窗
  const openModal = (banner?: BannerItem) => {
    if (banner) {
      setEditingBanner(banner)
      setForm({
        title: banner.title,
        description: banner.description || '',
        linkUrl: banner.linkUrl || '',
        linkType: banner.linkType,
        isActive: banner.isActive,
        sortOrder: banner.sortOrder,
        startTime: banner.startTime ? banner.startTime.toISOString().slice(0, 16) : '',
        endTime: banner.endTime ? banner.endTime.toISOString().slice(0, 16) : ''
      })
      setImagePreview(banner.imageUrl)
    } else {
      resetForm()
    }
    setShowModal(true)
  }

  // 关闭弹窗
  const closeModal = () => {
    setShowModal(false)
    resetForm()
  }

  // 处理图片上传
  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      if (!file.type.startsWith('image/')) {
        toast.error('请选择图片文件')
        return
      }
      if (file.size > 5 * 1024 * 1024) {
        toast.error('图片大小不能超过5MB')
        return
      }
      
      setForm(prev => ({ ...prev, image: file }))
      
      // 预览图片
      const reader = new FileReader()
      reader.onload = (e) => {
        setImagePreview(e.target?.result as string)
      }
      reader.readAsDataURL(file)
    }
  }

  // 保存轮播图
  const handleSave = async () => {
    if (!form.title.trim()) {
      toast.error('请填写标题')
      return
    }
    
    if (!editingBanner && !form.image) {
      toast.error('请选择图片')
      return
    }

    try {
      const formData = new FormData()
      formData.append('title', form.title)
      formData.append('description', form.description)
      formData.append('linkUrl', form.linkUrl)
      formData.append('linkType', form.linkType)
      formData.append('isActive', String(form.isActive))
      formData.append('sortOrder', String(form.sortOrder))
      if (form.startTime) formData.append('startTime', form.startTime)
      if (form.endTime) formData.append('endTime', form.endTime)
      if (form.image) formData.append('image', form.image)

      const url = editingBanner 
        ? `/v1/banner/admin/${editingBanner.id}`
        : '/v1/banner/admin/create'
      
      const method = editingBanner ? 'PUT' : 'POST'
      
      const response = await fetch(url, {
        method,
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: formData
      })
      
      const data = await response.json()
      
      if (data.success) {
        toast.success(editingBanner ? '更新成功' : '创建成功')
        closeModal()
        fetchBanners()
      } else {
        toast.error(data.message || '操作失败')
      }
    } catch (error) {
      console.error('保存失败:', error)
      toast.error('保存失败')
    }
  }

  // 删除轮播图
  const handleDelete = async (id: number) => {
    if (!confirm('确定要删除这个轮播图吗？')) {
      return
    }

    try {
      const response = await fetch(`/v1/banner/admin/${id}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      
      const data = await response.json()
      
      if (data.success) {
        toast.success('删除成功')
        fetchBanners()
      } else {
        toast.error(data.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      toast.error('删除失败')
    }
  }

  // 切换状态
  const toggleStatus = async (id: number, isActive: boolean) => {
    try {
      const response = await fetch('/v1/banner/admin/batch/status', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify({
          bannerIds: [id],
          isActive: !isActive
        })
      })
      
      const data = await response.json()
      
      if (data.success) {
        toast.success('状态更新成功')
        fetchBanners()
      } else {
        toast.error(data.message || '更新失败')
      }
    } catch (error) {
      console.error('更新状态失败:', error)
      toast.error('更新状态失败')
    }
  }

  // 调整排序
  const adjustOrder = async (id: number, direction: 'up' | 'down') => {
    const currentIndex = banners.findIndex(b => b.id === id)
    if (currentIndex === -1) return
    
    const targetIndex = direction === 'up' ? currentIndex - 1 : currentIndex + 1
    if (targetIndex < 0 || targetIndex >= banners.length) return
    
    // 交换排序
    const newBanners = [...banners]
    const temp = newBanners[currentIndex].sortOrder
    newBanners[currentIndex].sortOrder = newBanners[targetIndex].sortOrder
    newBanners[targetIndex].sortOrder = temp
    
    // 更新到服务器
    const bannerIds = newBanners
      .sort((a, b) => a.sortOrder - b.sortOrder)
      .map(b => b.id)
    
    try {
      const response = await fetch('/v1/banner/admin/batch/sort', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify({ bannerIds })
      })
      
      const data = await response.json()
      
      if (data.success) {
        fetchBanners()
      } else {
        toast.error(data.message || '排序更新失败')
      }
    } catch (error) {
      console.error('排序更新失败:', error)
      toast.error('排序更新失败')
    }
  }

  return (
    <div className="p-6 max-w-7xl mx-auto">
      {/* 头部 */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 mb-2">轮播图管理</h1>
          <p className="text-gray-600">管理小程序首页轮播图内容</p>
        </div>
        <Button onClick={() => openModal()} className="bg-blue-600 hover:bg-blue-700">
          <Plus className="w-4 h-4 mr-2" />
          新建轮播图
        </Button>
      </div>

      {/* 轮播图列表 */}
      <Card>
        <CardHeader>
          <CardTitle>轮播图列表</CardTitle>
          <CardDescription>
            共 {banners.length} 个轮播图，按排序显示
          </CardDescription>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="flex items-center justify-center h-32">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
            </div>
          ) : banners.length === 0 ? (
            <div className="text-center py-12 text-gray-500">
              <ImageIcon className="w-12 h-12 mx-auto mb-4 opacity-50" />
              <p>暂无轮播图</p>
            </div>
          ) : (
            <div className="space-y-4">
              {banners.map((banner, index) => (
                <div key={banner.id} className="border rounded-lg p-4 hover:shadow-md transition-shadow">
                  <div className="flex items-center space-x-4">
                    {/* 排序 */}
                    <div className="flex flex-col space-y-1">
                      <Button
                        variant="outline"
                        size="sm"
                        disabled={index === 0}
                        onClick={() => adjustOrder(banner.id, 'up')}
                        className="h-6 w-6 p-0"
                      >
                        <MoveUp className="w-3 h-3" />
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        disabled={index === banners.length - 1}
                        onClick={() => adjustOrder(banner.id, 'down')}
                        className="h-6 w-6 p-0"
                      >
                        <MoveDown className="w-3 h-3" />
                      </Button>
                    </div>

                    {/* 图片预览 */}
                    <div className="w-20 h-12 bg-gray-100 rounded overflow-hidden flex-shrink-0">
                      <img 
                        src={banner.imageUrl} 
                        alt={banner.title}
                        className="w-full h-full object-cover"
                        onError={(e) => {
                          const target = e.target as HTMLImageElement
                          target.src = '/static/images/placeholder.jpg'
                        }}
                      />
                    </div>

                    {/* 信息 */}
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center space-x-2 mb-1">
                        <h3 className="font-medium truncate">{banner.title}</h3>
                        <Badge variant={banner.isActive ? 'default' : 'secondary'}>
                          {banner.isActive ? '启用' : '禁用'}
                        </Badge>
                        {banner.linkType === 'external' && (
                          <Badge variant="outline">
                            <ExternalLink className="w-3 h-3 mr-1" />
                            外链
                          </Badge>
                        )}
                      </div>
                      {banner.description && (
                        <p className="text-sm text-gray-600 truncate mb-1">{banner.description}</p>
                      )}
                      <div className="flex items-center text-xs text-gray-500 space-x-4">
                        <span>排序: {banner.sortOrder}</span>
                        <span>创建: {new Date(banner.createdAt).toLocaleDateString()}</span>
                        {banner.startTime && (
                          <span className="flex items-center">
                            <Calendar className="w-3 h-3 mr-1" />
                            {new Date(banner.startTime).toLocaleDateString()}
                          </span>
                        )}
                      </div>
                    </div>

                    {/* 操作按钮 */}
                    <div className="flex items-center space-x-2">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => toggleStatus(banner.id, banner.isActive)}
                      >
                        {banner.isActive ? (
                          <>
                            <EyeOff className="w-4 h-4 mr-1" />
                            禁用
                          </>
                        ) : (
                          <>
                            <Eye className="w-4 h-4 mr-1" />
                            启用
                          </>
                        )}
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => openModal(banner)}
                      >
                        <Edit className="w-4 h-4 mr-1" />
                        编辑
                      </Button>
                      <Button
                        variant="destructive"
                        size="sm"
                        onClick={() => handleDelete(banner.id)}
                      >
                        <Trash2 className="w-4 h-4 mr-1" />
                        删除
                      </Button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* 新建/编辑弹窗 */}
      {showModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <Card className="w-full max-w-2xl max-h-[90vh] overflow-y-auto m-4">
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle>
                  {editingBanner ? '编辑轮播图' : '新建轮播图'}
                </CardTitle>
                <Button variant="ghost" size="sm" onClick={closeModal}>
                  <X className="w-4 h-4" />
                </Button>
              </div>
            </CardHeader>
            <CardContent className="space-y-4">
              {/* 图片上传 */}
              <div>
                <Label htmlFor="image">轮播图片 *</Label>
                <div className="mt-2">
                  {imagePreview ? (
                    <div className="relative">
                      <img 
                        src={imagePreview} 
                        alt="预览"
                        className="w-full h-48 object-cover rounded-lg border"
                      />
                      <div className="absolute inset-0 bg-black/50 opacity-0 hover:opacity-100 transition-opacity rounded-lg flex items-center justify-center">
                        <Button
                          variant="secondary"
                          size="sm"
                          onClick={() => document.getElementById('image-input')?.click()}
                        >
                          <Upload className="w-4 h-4 mr-2" />
                          重新上传
                        </Button>
                      </div>
                    </div>
                  ) : (
                    <div 
                      className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-gray-400 cursor-pointer"
                      onClick={() => document.getElementById('image-input')?.click()}
                    >
                      <Upload className="w-8 h-8 mx-auto mb-2 text-gray-400" />
                      <p className="text-sm text-gray-600">点击上传图片</p>
                      <p className="text-xs text-gray-400 mt-1">支持 JPG、PNG 格式，大小不超过 5MB</p>
                    </div>
                  )}
                  <input
                    id="image-input"
                    type="file"
                    accept="image/*"
                    onChange={handleImageChange}
                    className="hidden"
                  />
                </div>
              </div>

              {/* 基本信息 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="title">标题 *</Label>
                  <Input
                    id="title"
                    value={form.title}
                    onChange={(e) => setForm(prev => ({ ...prev, title: e.target.value }))}
                    placeholder="请输入标题"
                  />
                </div>
                <div>
                  <Label htmlFor="sortOrder">排序</Label>
                  <Input
                    id="sortOrder"
                    type="number"
                    value={form.sortOrder}
                    onChange={(e) => setForm(prev => ({ ...prev, sortOrder: parseInt(e.target.value) || 1 }))}
                  />
                </div>
              </div>

              <div>
                <Label htmlFor="description">描述</Label>
                <Textarea
                  id="description"
                  value={form.description}
                  onChange={(e) => setForm(prev => ({ ...prev, description: e.target.value }))}
                  placeholder="请输入描述"
                  rows={3}
                />
              </div>

              {/* 链接设置 */}
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <Label htmlFor="linkType">链接类型</Label>
                  <Select value={form.linkType} onValueChange={(value) => setForm(prev => ({ ...prev, linkType: value as any }))}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="none">无链接</SelectItem>
                      <SelectItem value="internal">内部页面</SelectItem>
                      <SelectItem value="external">外部链接</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="col-span-2">
                  <Label htmlFor="linkUrl">链接地址</Label>
                  <Input
                    id="linkUrl"
                    value={form.linkUrl}
                    onChange={(e) => setForm(prev => ({ ...prev, linkUrl: e.target.value }))}
                    placeholder={form.linkType === 'external' ? 'https://' : '/pages/'}
                    disabled={form.linkType === 'none'}
                  />
                </div>
              </div>

              {/* 时间设置 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="startTime">开始时间</Label>
                  <Input
                    id="startTime"
                    type="datetime-local"
                    value={form.startTime}
                    onChange={(e) => setForm(prev => ({ ...prev, startTime: e.target.value }))}
                  />
                </div>
                <div>
                  <Label htmlFor="endTime">结束时间</Label>
                  <Input
                    id="endTime"
                    type="datetime-local"
                    value={form.endTime}
                    onChange={(e) => setForm(prev => ({ ...prev, endTime: e.target.value }))}
                  />
                </div>
              </div>

              {/* 状态设置 */}
              <div className="flex items-center space-x-2">
                <Switch
                  id="isActive"
                  checked={form.isActive}
                  onCheckedChange={(checked) => setForm(prev => ({ ...prev, isActive: checked }))}
                />
                <Label htmlFor="isActive">启用状态</Label>
              </div>

              {/* 操作按钮 */}
              <div className="flex justify-end space-x-3 pt-4 border-t">
                <Button variant="outline" onClick={closeModal}>
                  取消
                </Button>
                <Button onClick={handleSave}>
                  <Save className="w-4 h-4 mr-2" />
                  保存
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      )}
    </div>
  )
}